package com.jeeplus.test.website.websiteFile.controller;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.file.config.FileProperties;
import com.jeeplus.file.repository.AccessoryRepository;
import com.jeeplus.test.tools.resp.R;
import com.jeeplus.test.tools.resp.ZyPage;
import com.jeeplus.test.tools.resp.ZyPageRequest;
import com.jeeplus.test.tools.utils.MinioUtil;
import com.jeeplus.test.website.websiteFile.domain.entity.WebsiteFile;
import com.jeeplus.test.website.websiteFile.domain.vo.WebsiteFileReqVo;
import com.jeeplus.test.website.websiteFile.domain.vo.WebsiteFileRespVo;
import com.jeeplus.test.website.websiteFile.service.WebsiteFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Api(tags = "网站管理-文件")
@RestController
@Slf4j
@RequestMapping("/websiteFile")
public class WebsiteFileController {
    @Autowired
    private WebsiteFileService websiteFileService;
    @Autowired
    private FileProperties fileProperties;

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private AccessoryRepository accessoryRepository;

    private static final String FILE_SERVER = "file";

    @Value("${config.accessory.minIO.endpoint}")
    private String systemMac;


    @ApiOperation("分页查询")
    @GetMapping("/page")
    public R<ZyPage<WebsiteFileRespVo>> getContentPage(WebsiteFileReqVo websiteFileReqVo, ZyPageRequest pageRequest) {
        long current = pageRequest.getPageNo();
        long size = pageRequest.getPageSize();
        Page<WebsiteFileRespVo> pageResult = websiteFileService.getContentPage(websiteFileReqVo, current, size);
        List<WebsiteFileRespVo> dataList = pageResult.getRecords();
        long total = pageResult.getTotal();
        ZyPage<WebsiteFileRespVo> retPage = ZyPage.getPage(dataList, pageRequest, total);
        return R.suc(retPage);
    }

    @ApiOperation("通过主键查询")
    @GetMapping("/queryById/{id}")
    public R<WebsiteFileRespVo> queryById(@PathVariable("id") String id) {
        WebsiteFileRespVo websiteFileRespVo = websiteFileService.queryById(id);
        return R.suc(websiteFileRespVo);
    }

    @ApiOperation("新增")
    @PostMapping("/add")
    public R addContent(WebsiteFileReqVo websiteFileReqVo) {
        return BooleanUtil.isTrue(websiteFileService.addContent(websiteFileReqVo)) ? R.suc() : R.error();
    }

    @ApiOperation("修改")
    @GetMapping("/update")
    public R updateContent(WebsiteFileReqVo websiteFileReqVo) throws ParseException {
        return BooleanUtil.isTrue(websiteFileService.updateContent(websiteFileReqVo)) ? R.suc() : R.error();
    }

    @ApiOperation("删除")
    @DeleteMapping("/delete/{id}")
    public R deleteContent(@PathVariable("id") String id) {
        return BooleanUtil.isTrue(websiteFileService.deleteContent(id)) ? R.suc() : R.error();
    }

    @ApiOperation("文件存储")
    @PostMapping("/upload/file")
    public ResponseEntity upload(HttpServletRequest request, MultipartFile file, HttpServletResponse response) throws Exception {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        String uploadPath = "/file/test" + "/" + year + "/" + month + "/";
        String minioPath = "/test" + "/" + year + "/" + month + "/";
        // 判断文件是否为空
        if (!file.isEmpty()) {
            String name = file.getOriginalFilename();
            if (fileProperties.isAvailable(name)) {
                // 文件保存路径
                // 转存文件
                accessoryRepository.save(file, minioPath, name);
                WebsiteFile websiteFile = new WebsiteFile();
                websiteFile.setId(IdUtil.simpleUUID());
                websiteFile.setFileUrl(systemMac + "/" + FILE_SERVER + uploadPath + name);
                websiteFile.setFileName(name);
                websiteFile.setBucketName(uploadPath);
                websiteFile.setBucketId(FILE_SERVER);
                websiteFile.setCreateTime(new Date());
                websiteFileService.save(websiteFile);
                return ResponseEntity.ok(websiteFile.getId());
            } else {
                return ResponseEntity.badRequest().body("请勿上传非法文件!");
            }
        } else {
            return ResponseEntity.badRequest().body("文件不存在!");
        }
    }

    @PostMapping("/upload/filetimestamp")
    public ResponseEntity<?> uploadtimestamp(HttpServletRequest request, MultipartFile file, HttpServletResponse response) throws Exception {
        Logger logger = LoggerFactory.getLogger(this.getClass());

        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        String uploadPath = "/test" + "/" + year + "/" + month + "/";
        String minioPath = "/test" + "/" + year + "/" + month + "/";

        long timestamp = System.currentTimeMillis();
        logger.info("开始处理文件上传，时间戳：{}", timestamp);

        if (!file.isEmpty()) {
            String originalName = file.getOriginalFilename();
            logger.info("上传的原始文件名：{}", originalName);

            if (fileProperties.isAvailable(originalName)) {
                String fileNameWithTimestamp;
                int dotIndex = originalName.lastIndexOf(".");
                if (dotIndex > 0) {
                    String namePart = originalName.substring(0, dotIndex);
                    String extPart = originalName.substring(dotIndex);
                    fileNameWithTimestamp = namePart + "_" + timestamp + extPart;
                } else {
                    fileNameWithTimestamp = originalName + "_" + timestamp;
                }
                logger.info("处理后的文件名：{}", fileNameWithTimestamp);

                try {
                    // 转存文件（使用带时间戳的文件名）
                    accessoryRepository.save(file, minioPath, fileNameWithTimestamp);
                    logger.info("文件已成功保存到存储系统");

                    WebsiteFile websiteFile = new WebsiteFile();
                    websiteFile.setId(IdUtil.simpleUUID());
                    websiteFile.setFileUrl(systemMac + "/" + FILE_SERVER + uploadPath + fileNameWithTimestamp);
                    websiteFile.setFileName(fileNameWithTimestamp);
                    websiteFile.setBucketName(uploadPath);
                    websiteFile.setBucketId(FILE_SERVER);
                    websiteFile.setCreateTime(new Date());

                    // 保存到数据库
                    boolean saveSuccess = websiteFileService.save(websiteFile);
                    if (saveSuccess) {
                        logger.info("文件信息已成功保存到数据库，ID：{}，存储的文件名为：{}",
                                websiteFile.getId(), fileNameWithTimestamp);
                        return ResponseEntity.ok(websiteFile.getId());
                    } else {
                        logger.error("数据库保存失败，save方法返回false");
                        return ResponseEntity.status(500).body("文件信息保存到数据库失败");
                    }
                } catch (Exception e) {
                    logger.error("文件上传过程中发生错误", e);
                    return ResponseEntity.status(500).body("文件上传失败：" + e.getMessage());
                }
            } else {
                logger.warn("文件格式不合法：{}", originalName);
                return ResponseEntity.badRequest().body("请勿上传非法文件!");
            }
        } else {
            logger.warn("上传的文件为空");
            return ResponseEntity.badRequest().body("文件不存在!");
        }
    }



    @ApiOperation("下载文件流")
    @GetMapping(value ="downloadFile", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<StreamingResponseBody> downloadFile(String id) throws Exception {
        WebsiteFileRespVo websiteFileRespVo = websiteFileService.queryById(id);
        String uploadPath = websiteFileRespVo.getBucketName().replace("/file/","");
        String name = websiteFileRespVo.getFileName();
        String encode = URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
        File file =  accessoryRepository.get ( uploadPath, name );
        return ResponseEntity.ok()
                .contentType( MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encode)
                .body(outputStream -> {
                    try (InputStream inputStream = Files.newInputStream(file.toPath())) {
                        StreamUtils.copy(inputStream, outputStream);
                    } catch (IOException ignored) {

                    }
                });
    }



}
